#include "mythread.h"
#include <QDateTime>

#include <QDebug>


MyThread::MyThread(QObject *parent) : QThread(parent){}

void MyThread::run()
{
    stopFlag    = false;

    QTcpSocket tcpSocket;
    QByteArray dataStream;
    QByteArray frame;
    tcpSocket.connectToHost(ip, port);
    if(!tcpSocket.waitForConnected()){//等待连接请求成功
        emit errorState("Server unreachable!");
        stopFlag = true;
        return;
    }

    dataStream.clear();
    dataStream = "?action=stream\n";
    tcpSocket.write(dataStream);
    if(!tcpSocket.waitForBytesWritten()){//等待数据发送完毕
        emit errorState("Request sent fail!");
        return;
    }

    //删除报文头
    dataStream.clear();
    while(!dataStream.contains("\r\n\r\n")){
        tcpSocket.waitForReadyRead();
        dataStream.append(tcpSocket.readAll());
    }
    dataStream.remove(0, dataStream.indexOf("\r\n\r\n")+4);

    //提取数据
    while(!stopFlag){
        while(!dataStream.contains("\r\n--")){
            tcpSocket.waitForReadyRead();
            dataStream.append(tcpSocket.readAll());
        }
        dataStream.remove(0, dataStream.indexOf("\n\n")+2);//删除数据头
        frame = dataStream.mid(0, dataStream.indexOf("\r\n--"));//取出图片数据
        dataStream.remove(0, frame.size()+4);
        curImg.loadFromData(frame, "JPEG");
        emit curImgChanged(curImg);
    }
}

void MyThread::setHostAddress(QString ip, int port, QString addr)
{
    this->ip    = ip;
    this->port  = port;
    this->addr  = addr;
}

void MyThread::stopCapture()
{
    stopFlag = true;
}
